<template>
  <gz-table
    :config="config"
    @handleCurrentChange="handleCurrentChange"
    @handleSizeChange="handleSizeChange"
  >
    <!-- 基本列插槽 -->
    <!-- <template #nameExpand="{ row: scope }">  </template> -->
    <!-- 操作列插槽 -->
    <template #handle="{ row: scope }">
      <el-button type="primary" @click="editClick(scope)">
        编辑
      </el-button>
      <el-button type="danger" @click="removeClick(scope)">
        删除
      </el-button>
    </template>
  </gz-table>
  <el-dialog
    title="编辑"
    v-model="dialogVisible"
    v-if="dialogVisible"
    width="900px"
  >
    <database-dialog
      ref="databaseRef"
      :databaseConfig="databaseConfig"
    ></database-dialog>
    <template #footer>
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="editSubmit">确 定</el-button>
    </template>
  </el-dialog>
</template>

<script>
import databaseDialog from "@/views/addData/components/databaseDialog.vue";
import gzTable from "@/components/table/index.vue";

import { reactive, toRefs, ref, onMounted, watch } from "vue";
export default {
  components: {
    gzTable,
    databaseDialog
  },
  setup() {
    const databaseRef = ref(null);
    const dialogVisible = ref(false);
    const columnDialogVisible = ref(false);
    const state = reactive({
      rowId: "", // 每行数据源id
      config: {
        // 表格样式
        style: {
          stripe: true,
          border: true,
          maxHeight: 700
        },
        loading: false,
        // 分页设置
        pagination: {
          current: 1,
          limit: 10,
          total: 0
        },
        // 列
        column: [
          {
            prop: "index",
            type: "index",
            label: "序号",
            width: 50
          },
          {
            prop: "tableName",
            label: "数据表名称",
            width: 265
          },
          {
            prop: "primaryKeys",
            label: "主键",
            width: 300,
            formatter(value) {
              if (value.primaryKeys && value.primaryKeys.length > 0) {
                return value.primaryKeys.join("");
              } else {
                return "-";
              }
            }
          },
          {
            prop: "tableColumns",
            label: "列名",
            width: 500,
            formatter(value) {
              if (value.tableColumns && value.tableColumns.length > 0) {
                let columns = value.tableColumns.map((item) => {
                  return item.columnName;
                });
                if (columns && columns.length > 0) {
                  return columns.join("，");
                } else {
                  return "-";
                }
              } else {
                return "-";
              }
            }
          },
          {
            prop: "remarks",
            label: "数据表描述",
            width: 350
          },
          {
            type: "operate",
            label: "操作",
            width: 200,
            fixed: "right",
            slotName: "handle"
          }
        ],
        tableData: []
      },
      // 数据表弹框组件 配置
      databaseConfig: {
        tableName: "",
        remarks: "",
        tableData: []
      }
    });
    onMounted(() => {
      getTableData();
    });

    const getTableData = async () => {
      try {
        state.config.loading = true;
        let result = await vm.$store.dispatch("GET_DATA_TABLELIST", {
          limit: state.config.pagination.limit, //当前页最大显示数
          page: state.config.pagination.current //当前页
        });
        state.config.tableData = result.records;
        state.config.pagination.total = result.total;
        state.config.pagination.current = result.current;
        state.config.loading = false;
      } catch (error) {
        console.log(error);
      }
    };
    const handleSizeChange = (val) => {
      state.config.pagination.limit = val;
      getTableData();
    };
    const handleCurrentChange = (val) => {
      state.config.pagination.current = val;
      getTableData();
    };
    // 编辑回显数据
    const editClick = (rowData) => {
      let result = vm.$tool.deepClone(rowData);
      state.rowId = result.id;
      state.databaseConfig.id = result.id;
      state.databaseConfig.tableName = result.tableName;
      state.databaseConfig.remarks = result.remarks;
      state.databaseConfig.tableData = result.tableColumns;

      dialogVisible.value = true;
    };
    // 编辑数据表 确定
    const editSubmit = () => {
      let { id, tableData, tableName } = databaseRef.value.databaseConfig;
      let remarks = databaseRef.value.tableRemarks;
      vm.$axios
        .post("/api/v1/dataengine/dataTable/edit", {
          id,
          tableName,
          remarks,
          primaryKeys: tableData
            .filter((t) => t.primaryKey)
            .map((p) => p.columnName),
          tableColumns: tableData.map((t) => {
            return {
              id: t.id,
              columnName: t.columnName,
              columnType: t.columnType,
              charOctetLength: t.charOctetLength,
              remarks: t.remarks,
              autoincrement: t.autoincrement,
              primaryKey: t.primaryKey
            };
          })
        })
        .then((res) => {
          vm.$message.success("编辑数据表成功！");
          dialogVisible.value = false;
          getTableData();
        })
        .catch(() => {});
    };
    const removeClick = (rowData) => {
      vm.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          let result = await vm.$store.dispatch(
            "DELETE_DATA_TABLELIST",
            rowData.id
          );
          if (result) {
            vm.$message.success("删除成功!");
            getTableData();
          }
        })
        .catch(() => {
          vm.$message.success("已取消删除!");
        });
    };

    // 打开 列映射关系弹框
    const addDatabaseDialog = () => {
      columnDialogVisible.value = true;
    };
    // 成功新建数据库表 后回调
    const tableSuccessBuild = () => {
      // 调用 获取数据库表 方法
    };

    return {
      databaseRef,
      dialogVisible,
      columnDialogVisible,
      ...toRefs(state),
      getTableData,
      handleSizeChange,
      handleCurrentChange,
      editClick,
      editSubmit,
      removeClick,
      addDatabaseDialog,
      tableSuccessBuild
    };
  }
};
</script>

<style scoped>
.edit-form .item-inline {
  width: 50%;
  display: inline-block;
}
.addData-form-pretreatmentCode >>> .el-input__inner {
  border-top-right-radius: 0;
  border-bottom-right-radius: 0;
}
.addData-form-pretreatmentCode >>> .el-button {
  border-top-left-radius: 0;
  border-bottom-left-radius: 0;
  margin-top: -1px;
}
</style>
